#!/usr/bin/python
# coding:utf-8

import os

_root = os.path.abspath(os.path.dirname(__file__)).replace('\\', '/')
# 打包用
# _root = os.path.dirname(os.path.realpath(sys.executable))


_jsonPath = _root + "/json"
_sameJsonPath = _root + "/samejson"
_fileSavePath = _root + "/game/manage/config"


# 生成json go文件
def generateJsonGo(fileName):
    _fileName = fileName.split(".json")[0]
    if _fileName in ["timer", "crosstimer"]:
        return

    _filePath = f"{_fileSavePath}/config_{_fileName}.go"
    # 文件不存在创建文件
    if not os.path.exists(_filePath):
        with open(_filePath, "w") as f:
            f.write("")

    _fileLines = []
    with open(_filePath, "r", encoding="utf-8") as f:
        _fileLines = f.readlines()

    # 已生成不处理
    if _fileLines:
        return

    # 文件包头
    _fileLines.append("package config\r\n")

    # 定义结构体
    _fileLines.append(f"type {_fileName} struct " + "{\n    *JsonHandle\n    // 预处理字段定义区域---start\n\n    // 预处理字段定义区域---end\n}\n\n")

    # init方法定义
    _fileLines.append(
        "func init() {\n"
        + f"    config := &{_fileName}"
        + "{\n        " + f'JsonHandle: NewJsonHandle("{_fileName}"),\n'
        + "    }\n"
    )
    _fileLines.append(f"    Manage.configs.{_fileName} = config\n")
    _fileLines.append("    RegisterConfigInterface(config.Name, config)\n}\n\n")

    # Load方法定义
    _fileLines.append("// Load 加载配置\n")
    _fileLines.append(f"func (self *{_fileName}) Load(jsonData any) error " + "{\n    ")
    _fileLines.append("err := self.JsonHandle.Load(jsonData)\n    if err != nil {\n        return err\n    }\n")
    _fileLines.append(f"    self.PreConfig()\n    return nil\n" + "}\n\n")

    # PreConfig配置预处理
    _fileLines.append("// PreConfig 配置预处理\n")
    _fileLines.append(f"func (self *{_fileName}) PreConfig() " + "{\n\n}")

    _fileLines.append("\n\n// ------------------------ 以上文件内容自动生成,请勿随便修改! ------------------------\n")
    _fileLines.append("// ------------------------ 下方、定义配置diy方法 ------------------------\n\n")

    with open(_filePath, "w", encoding="utf-8") as f:
        f.writelines(_fileLines)


# json目录文件转go
def json2Go():
    _fileList = os.listdir(_jsonPath)
    for file in _fileList:
        # 文件夹不处理
        if os.path.isdir(file):
            continue

        generateJsonGo(file)


# 生成samejson go文件
def generateSamejsonGo(fileName):
    _fileName = fileName.split(".json")[0].split("_")[1]
    _filePath = f"{_fileSavePath}/config_{_fileName}.go"
    # 文件不存在创建文件
    if not os.path.exists(_filePath):
        with open(_filePath, "w") as f:
            f.write("")

    _fileLines = []
    with open(_filePath, "r", encoding="utf-8") as f:
        _fileLines = f.readlines()

    # 已生成不处理
    if _fileLines:
        return

    # _toFileName = _fileName[:1].lower() + _fileName[1:]
    _toFileName = _fileName
    _cfgName = "Game" + _toFileName

    # 文件包头
    _fileLines.append("package config\r\n")
    # import
    _fileLines.append('import cfg "gogame/game/manage/config/structs"\n\n')
    # 定义结构体
    _fileLines.append(
        f"type {_fileName} struct " +
        "{\n    StructHandle\n    *cfg." + f"{_cfgName}" +
        "\n    NewFunc func(_buf []map[string]any) (*cfg." + f"{_cfgName}" + ", error) // 数据生成方法\n\n" +
        "    // 预处理字段定义区域---start\n\n    // 预处理字段定义区域---end\n"
        "}\n\n"
    )
    # init方法定义
    _fileLines.append(
        "func init() {\n"
        + f"    config := &{_fileName}"
        + "{\n        " + f'StructHandle: NewStructHandle("game_{_fileName}"),'
        + "\n        NewFunc:      cfg.NewGame" + f"{_toFileName},"
        + "\n    }\n"
    )
    _fileLines.append(f"    Manage.configs.{_fileName} = config\n")
    _fileLines.append("    RegisterConfigInterface(config.Name, config)\n")
    _fileLines.append("}\n\n")
    # Load方法定义
    _fileLines.append("// Load 加载配置\n")
    _fileLines.append(f"func (self *{_fileName}) Load(jsonData any) error " + "{\n    ")
    _fileLines.append("data, err := self.NewFunc(jsonData.([]map[string]any))\n    if err != nil {\n        return err\n    }\n    ")
    _fileLines.append(f"self.Game{_toFileName} = data\n    self.PreConfig()\n    return nil\n" + "}\n\n")
    # PreConfig配置预处理
    _fileLines.append("// PreConfig 配置预处理\n")
    _fileLines.append(f"func (self *{_fileName}) PreConfig() " + "{\n\n}")

    _fileLines.append("\n\n// ------------------------ 以上文件内容自动生成,请勿随便修改! ------------------------\n")
    _fileLines.append("// ------------------------ 下方、定义配置diy方法 ------------------------\n\n")

    with open(_filePath, "w", encoding="utf-8") as f:
        f.writelines(_fileLines)


# samejson目录文件转go
def samejson2Go():
    _fileList = os.listdir(_sameJsonPath)
    for file in _fileList:
        # 文件夹不处理
        if os.path.isdir(file):
            continue

        generateSamejsonGo(file)


def run():
    json2Go()
    samejson2Go()


if __name__ == '__main__':
    run()
